//
//  HRLoginPage.swift
//  weiBo
//
//  Created by helong on 16/7/10.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

// -  app标示符号
let appKey = "3002178164"
//  -  密文
let appSecret = "be4a0f09d3c9578cb82e0d9d79c61cc1"
//  -  请求成功返回网址(会再网址后面拼接授权码)
let Redirect_Uri = "http://www.baidu.com"

class HRLoginPage: UIViewController {

     //  - 懒加载网页webview控件
    private lazy var webView:UIWebView = UIWebView()
    

 // MARK: - 设置view为webview
    /**
     加载的view的时候调用
     */
    override func loadView() {
        
        //设置view为UIWebView,并遵守协议
        webView.opaque = false//背景颜色不透明
        view = webView
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.yellowColor()
//        self.automaticallyAdjustsScrollViewInsets = false
        
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelButtonClicked")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", target: self, action: "autoFillButtonClicked")
        
        requestAuthCode()
        
    }
    
 // MARK: - 请求开放授权页面
    /**
     请求开放授权页面
     */
    func requestAuthCode(){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(Redirect_Uri)"
//        let request = NSURLRequest(URL: NSURL(fileURLWithPath: url))
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        webView.loadRequest(request)
    }
    
    //MARK: - 导航栏的按钮的点击事件
     // MARK: -取消按钮点击事件
    func cancelButtonClicked(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
     // MARK: -自动填充密码按钮点击事件
    func autoFillButtonClicked(){
    
            //自动填充执行js代码
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('passwd').value = 'he1990423110';document.getElementById('passwd').focus();document.getElementById('userId').value = 'helong_whatever@163.com'")
        
    }
    
   
}
// MARK: - 遵守网络请求的代理
extension HRLoginPage: UIWebViewDelegate{
    // MARK: - 截取请求成功之后返回网页拼接的授权码
    //将要发送请求的时候调用,通过返回值判断是否加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //保证请求回来的URL有值
        guard let url = request.URL else {
            return false
        }
       
       
        //url一定有值
        if !url.absoluteString.hasPrefix(Redirect_Uri) {
            return true
        }
    
        if let query1 = url.query where query1.hasPrefix("code="){
            
            let code = query1.substringFromIndex("code=".endIndex)
            
            //获取到code之后根据code获取access_token
            HRUserAccountInfos.sharedUserAccount.requestAccessToken(code, callBack: { (success) -> () in
                if success {//获取用户数据成功的逻辑
                    
                    //  因为是present出来的额,一定要dismiss掉,否则会有内存泄漏
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //切换到登录成功之后的欢迎页面,将根控制器切换成欢迎页面(使用通知)
                    NSNotificationCenter.defaultCenter().postNotificationName(switchControllerNotificationName, object: self)
                })

                }else{//获取用户数据失败的逻辑
                    
                    
                    
                }
            })
            
        }else{//当用户取消授权的时候退出页面
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
        
    }
    /**
     开始网络请求
     */
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    /**
     完成网络请求
     */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
  
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}